#include <iostream>
#include "Socket.hpp"

/*
    Client端
    1. 创建socket套接字
    2. 建立链接Connect (需要bind, 但是不需要显示的bind)
    3. 向Server端发送消息/接收Server端消息
*/

// 调用方式 ./TCPClient Server_ip Server_port
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        std::cerr << "User: " << argv[0] << " Server_ip" << " Server_port";
        exit(-1);
    }

    std::string Server_ip = argv[1];
    uint16_t Server_port = std::stoi(argv[2]);

    /* 1. 创建套接字Socket */
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "Socket err!" << std::endl;
        exit(-2);
    }

    /* 2. connect 链接 */
    InterAddr server(Server_ip, Server_port);
    int n = connect(sockfd, (const sockaddr *)&server.Get_addr(), server.Get_Len());
    if(n < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(-3);
    }

    /* 3. 向Server端发送消息/接收Server端消息 */
    while(true)
    {
        /* [1] 向Server端发送消息 */
        std::string input;
        std::cout << "Please Enter# ";
        std::getline(std::cin, input);
        write(sockfd, input.c_str(), input.size());

        /* [2] 接收Server端消息 */
        char output[1024];
        ssize_t size = read(sockfd, output, sizeof(output) - 1);
        if(size > 0)
        {
            output[size] = 0;
            std::cout << "server echo# " << output << std::endl;
        }
    }

    /* 关闭网络套接字 */
    close(sockfd);
    
    return 0;
}